/* eslint-disable no-shadow */
/**
 * 脉脉直聘
 */
import React from 'react';
import { Form, Input, Select, Button, message, Card, Icon, Alert, Spin, InputNumber, Row, Col } from 'antd';
import { BottomAction } from '@/components';
import { useRequest, defaultFormatResult } from '@/hooks';
import useChannelDict from './useChannelDict';
import DropDownCascader from '../../Setting/containers/DropDownCascader';
import { getCategoryTree, getPositionKeywords } from '../../Setting/service';
import useRecruitOutwardsChannelDetail from './useRecruitOutwardsChannelDetail';
import useRecruitOutwardsChannelUpdate from './useRecruitOutwardsChannelUpdate';

const { Option } = Select;
const channelCode = 'mmzp';

const renderMonthForm = () => {
    const arr = [];
    for (let i = 12; i <= 24; i += 1) {
        arr.push(i);
    }
    return arr.map(item => (
        <Option value={item} key={item}>
            {item}
        </Option>
    ));
};
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
    }
};
const filterTree = tree =>
    tree.map(({ children, positionCategoryCode, positionCategoryName, ...props }) => ({
        children: children && children.length > 0 ? filterTree(children) : '',
        label: positionCategoryName,
        value: positionCategoryCode,
        ...props
    }));
const flat = (tree, parent) =>
    tree.reduce((pre, curr) => {
        const { children, label, value } = curr;
        const item = { label, value, parent };
        let next = [item];
        if (children && children.length) {
            next = [...next, ...flat(children, item)];
        }
        return [...pre, ...next];
    }, []);
const SalaryUnitWrapper = ({ children }) => <span style={{ margin: '0 8px', fontWeight: 'bolder' }}>{children}</span>;

function MaimaiForm({ form, outwardId, onSuccess, onError }) {
    const { getFieldDecorator, getFieldsValue, getFieldValue, validateFields } = form;
    const { workExperience, educationDegree, loading: dictLoading } = useChannelDict(channelCode, [
        'workExperience',
        'educationDegree'
    ]);
    const [secondaryShow, setSecondaryShow] = React.useState(true);
    // 行业
    const { data: categoryTree, loading: categoryLoading } = useRequest(() => getCategoryTree(channelCode), {
        refreshDeps: [],
        formatResult: res => {
            if (res) {
                const { code, data: resData, msg } = res;
                if (code === 10000) {
                    return filterTree(resData || []);
                }
                message.error(msg);
            }
            return null;
        }
    });
    // 行业方向
    const { data: keywords, loading: keywordLoading, run: fetchKeywords, mutate: resetKeywords } = useRequest(
        positionCategoryCodeList =>
            getPositionKeywords({
                channelCode,
                positionCategoryCodeList
            }),
        {
            manual: true,
            initialData: [],
            ...defaultFormatResult
        }
    );

    // 人才方向
    const {
        data: secondaryKeyWords,
        loading: secondaryKeyWordsLoading,
        run: fetchSecondaryKeyWords,
        mutate: resetSecondaryKeywords
    } = useRequest(key => getPositionKeywords({ channelCode, positionCategoryCodeList: [key], level: 'lv2' }), {
        manual: true,
        initialData: [],
        ...defaultFormatResult,
        onSuccess: d => {
            setSecondaryShow(!!(d && d.length));
        }
    });

    const [runSubmit, submitLoading] = useRecruitOutwardsChannelUpdate(onSuccess, onError);
    const [data, loading] = useRecruitOutwardsChannelDetail(outwardId, channelCode);

    // 行业中使用的组件DropDownCascader存在问题： onChange事件只要值变化就会触发（不是手动选择后触发），因而添加了这个状态去控制职位关键词是否清空
    const firstChangeRef = React.useRef(false);

    // 行业变化
    const handleChange = keys => {
        if (keys && keys.length > 0) {
            fetchKeywords(keys);
        } else {
            resetKeywords([]);
        }
        if (firstChangeRef.current) {
            firstChangeRef.current = !firstChangeRef.current;
        } else {
            form.setFieldsValue({
                major_new: undefined, // 设置行业方向为空
                major_new_lv2: undefined // 设置人才方向为空
            });
        }
    };

    // 行业方向变化
    const handleMajorChange = () => {
        form.setFieldsValue({
            major_new_lv2: undefined // 设置人才方向为空
        });
    };

    React.useEffect(() => {
        const val = form.getFieldValue('major_new');
        if (!val) {
            resetSecondaryKeywords([]); // 人才方向字典
        } else {
            fetchSecondaryKeyWords(val); // 人才方向字典
        }
    }, [form.getFieldValue('major_new')]);

    // 初始化
    React.useEffect(() => {
        const channelRecruitInfo = JSON.parse(data?.channelRecruitInfo || null);
        if (!channelRecruitInfo) {
            return;
        }
        const { profession_new } = channelRecruitInfo;
        firstChangeRef.current = true;

        const extend = {
            profession_new: profession_new ? [profession_new] : []
        };
        const values = { ...channelRecruitInfo, ...extend };
        const formValues = getFieldsValue();
        const exists = key => Object.keys(formValues).indexOf(key) !== -1;
        form.setFieldsValue(
            Object.keys(values).reduce((pre, curr) => {
                if (exists(curr)) {
                    return { ...pre, [curr]: values[curr] };
                }
                return { ...pre };
            }, {})
        );
    }, [data, categoryTree]);
    const handleSubmit = e => {
        e.preventDefault();
        form.validateFieldsAndScroll(async (err, values) => {
            if (err) {
                return;
            }
            const findLabel = (dict, val, options = { value: 'value', label: 'label' }) => {
                const { value, label } = options;
                if (!dict || !dict.length || !val) {
                    return undefined;
                }
                return dict.find(item => item[value] === val)?.[label];
            };
            const keywordOption = { value: 'skillId', label: 'skill' };
            const sourceData = JSON.parse(data?.channelRecruitInfo || null) || {}; // shit,将后端返回的未展示在界面上的数据原封不动传至后台
            const { profession_new, major_new, major_new_lv2 } = values;
            const professionVal = profession_new?.[0];
            const extend = {
                profession_new: professionVal,
                profession_text: findLabel(flat(categoryTree), professionVal),
                major_new_text: findLabel(keywords, major_new, keywordOption),
                major_new_lv2: secondaryKeyWords && secondaryKeyWords.length ? major_new_lv2 : '', // 因为非必填
                major_new_lv2_text: findLabel(secondaryKeyWords, major_new_lv2, keywordOption) || ''
            };
            runSubmit(outwardId, channelCode, JSON.stringify({ ...sourceData, ...values, ...extend }));
        });
    };
    // 标准的
    const renderOptions = dict => {
        if (!dict || !dict.length) {
            return null;
        }
        return dict.map(item => (
            <Option value={item.selectValue} key={item.selectValue}>
                {item.selectName}
            </Option>
        ));
    };
    const checkPrice = (rule, value, callback) => {
        const from = getFieldValue('salary_min');
        const to = getFieldValue('salary_max');
        const unit = getFieldValue('salary_share');
        if (!from || !to || !unit) {
            return callback('请输入薪资范围');
        }
        if (from - to > 0) {
            return callback('薪资最小值不能大于最大值');
        }
        if (from * 2 < to) {
            return callback('薪资最大值不能大于最小值的两倍');
        }
        return callback();
    };
    const handleForceValidate = keys => {
        validateFields(keys, { force: true });
    };
    React.useEffect(() => {
        handleForceValidate(['temp']);
    }, [getFieldValue('salary_min'), getFieldValue('salary_max')]);
    const renderSalaryForm = () =>
        getFieldDecorator('temp', {
            initialValue: 1,
            rules: [{ required: true, message: '\r' }, { validator: checkPrice }]
        })(
            <div style={{ display: 'flex' }}>
                <Form.Item label="" colon={false} style={{ width: '24%', marginBottom: 0 }}>
                    {getFieldDecorator('salary_min')(
                        <InputNumber
                            precision={0}
                            min={1000}
                            step={100}
                            style={{ width: '100%' }}
                            placeholder="输入整数"
                        />
                    )}
                </Form.Item>
                <SalaryUnitWrapper>-</SalaryUnitWrapper>
                <Form.Item label="" colon={false} style={{ width: '24%', marginBottom: 0 }}>
                    {getFieldDecorator('salary_max')(
                        <InputNumber
                            min={1000}
                            precision={0}
                            step={100}
                            style={{ width: '100%' }}
                            placeholder="输入整数"
                        />
                    )}
                </Form.Item>
                <SalaryUnitWrapper>*</SalaryUnitWrapper>
                <Form.Item label="" colon={false} style={{ width: '24%', marginBottom: 0 }}>
                    {getFieldDecorator('salary_share')(<Select placeholder="选择系数">{renderMonthForm()}</Select>)}
                </Form.Item>
                {/* <div style={{ marginLeft: 8 }}>{data?.companyCurrencyCode || '薪'}</div> */}
                <div style={{ marginLeft: 8 }}>薪</div>
            </div>
        );

    const renderWarnIcon = style => <Icon style={style || {}} type="warning" theme="twoTone" twoToneColor="#faad14" />;
    const renderWarnLabel = (text, required = true) => (
        <div style={{ position: 'relative', display: 'inline-block', overflowX: 'visible' }}>
            {renderWarnIcon({
                position: 'absolute',
                top: 14,
                left: required ? -30 : -18,
                fontSize: '12px'
            })}

            {text}
        </div>
    );

    return (
        <Card
            bordered={false}
            title={<div style={{ margin: '10px 0' }}>渠道发布信息</div>}
            loading={loading || dictLoading}
            extra={data?.channelLogoUrl && <img height="44" src={data?.channelLogoUrl || ''} alt="BOSS直聘" />}
        >
            <BottomAction>
                <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                    提交
                </Button>
            </BottomAction>
            <Alert
                style={{ marginBottom: 24 }}
                message={
                    <div>
                        注：加&nbsp;
                        {renderWarnIcon()}
                        &nbsp;内容在确认发布后，将无法修改
                    </div>
                }
                type="warning"
            />
            <Form {...formItemLayout} className="ant-advanced-search-form">
                <Form.Item label={renderWarnLabel('职位名称')}>
                    {getFieldDecorator('position', {
                        rules: [
                            { required: true, message: '请输入职位名称' },
                            {
                                validator: (rule, value, callback) => {
                                    if (value?.length > 25) {
                                        callback('职位名称最大长度不能超过25个字符');
                                        return;
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(<Input disabled={data?.hasRelease} placeholder="请输入职位名称" maxLength={25} />)}
                </Form.Item>

                <Form.Item label={renderWarnLabel('行业')}>
                    <Spin spinning={categoryLoading}>
                        {getFieldDecorator('profession_new', {
                            rules: [{ required: true, message: '请选择行业' }]
                        })(
                            <DropDownCascader
                                disabled={data?.hasRelease}
                                onChange={handleChange}
                                options={categoryTree || []}
                                placeholder="选择行业"
                                maxCount={1}
                                changeOnLastLevel={false}
                            />
                        )}
                    </Spin>
                </Form.Item>
                <Form.Item label={renderWarnLabel('行业方向')}>
                    <Spin spinning={keywordLoading}>
                        {getFieldDecorator('major_new', {
                            initialValue: undefined,
                            rules: [
                                {
                                    required: true,
                                    message: '行业方向不能为空'
                                }
                            ]
                        })(
                            <Select
                                showArrow
                                showSearch
                                allowClear
                                onChange={handleMajorChange}
                                style={{ width: '100%' }}
                                placeholder="请选择行业方向"
                                optionFilterProp="children"
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                            >
                                {keywords?.map(item => (
                                    <Option value={item.skillId} key={item.skillId}>
                                        {item.skill}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Spin>
                </Form.Item>
                {secondaryShow && (
                    <Form.Item label={renderWarnLabel('人才方向', false)}>
                        <Spin spinning={secondaryKeyWordsLoading}>
                            {getFieldDecorator('major_new_lv2', {
                                initialValue: undefined
                            })(
                                <Select
                                    showArrow
                                    showSearch
                                    allowClear
                                    style={{ width: '100%' }}
                                    placeholder="请选择人才方向"
                                    optionFilterProp="children"
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                >
                                    {secondaryKeyWords?.map(item => (
                                        <Option value={item.skillId} key={item.skillId}>
                                            {item.skill}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                )}
                <Form.Item label="经验和学历" required>
                    <Row>
                        <Col span={12}>
                            <Form.Item style={{ marginBottom: 0 }}>
                                {getFieldDecorator('work_time', {
                                    rules: [{ required: true, message: '请选择经验' }]
                                })(<Select placeholder="选择经验">{renderOptions(workExperience)}</Select>)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item style={{ marginBottom: 0, marginLeft: 20 }}>
                                {getFieldDecorator('degree', {
                                    rules: [{ required: true, message: '请选择学历' }]
                                })(<Select placeholder="选择学历">{renderOptions(educationDegree)}</Select>)}
                            </Form.Item>
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item label="工作地址">{getFieldDecorator('channelWorkCityName')(<Input disabled />)}</Form.Item>
                <Form.Item label="薪资范围">{renderSalaryForm()}</Form.Item>

                <Form.Item label="职位亮点">
                    {getFieldDecorator('custom_text', {
                        initialValue: undefined
                    })(<Input placeholder="输入职位亮点" maxLength={10} />)}
                </Form.Item>

                <Form.Item label="职位描述">
                    {getFieldDecorator('description', {
                        rules: [
                            { required: true, message: '请输入职位描述' },
                            {
                                validator: (rule, value, callback) => {
                                    if (value?.length > 10000) {
                                        callback('职位描述最大长度不能超过10000个字符');
                                        return;
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(<Input.TextArea rows={24} maxLength={10000} placeholder="请输入职位描述" />)}
                </Form.Item>
            </Form>
        </Card>
    );
}

export default Form.create({})(MaimaiForm);
